<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://git.oschina.net/wostech/wp-wxtpp
 * @since      1.0.0
 *
 * @package    WP_WXTPP
 * @subpackage WP_WXTPP/includes
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    WP_WXTPP
 * @subpackage WP_WXTPP/includes
 * @author     Yajun Hu <yjhu@126.com>
 */
class WP_WXTPP {

	/**
	 * The loader that's responsible for maintaining and registering all hooks that power
	 * the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      WP_WXTPP_Loader    $loader    Maintains and registers all hooks for the plugin.
	 */
	protected $loader;

	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $plugin_name    The string used to uniquely identify this plugin.
	 */
	protected $plugin_name;

	/**
	 * The current version of the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $version    The current version of the plugin.
	 */
	protected $version;

	/**
	 * Define the core functionality of the plugin.
	 *
	 * Set the plugin name and the plugin version that can be used throughout the plugin.
	 * Load the dependencies, define the locale, and set the hooks for the admin area and
	 * the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {

		$this->plugin_name = 'wp-wxtpp';
		$this->version = '1.0.0';                

		$this->load_dependencies();
		$this->set_locale();
                $this->set_endpoints();
                $this->loader->add_filter( 'admin_footer_text', $this, 'admin_footer_text' );
                $this->loader->add_filter( 'update_footer', $this, 'update_footer', 11 );
                $this->loader->add_action( 'login_form', $this, 'login_form' );
                $this->loader->add_action( 'login_head', $this, 'login_head' );
                $this->loader->add_filter( 'get_avatar', $this, 'get_avatar', 1, 5 );
                $this->loader->add_action( 'init', 'WXTPP_GH', 'init' );
                $this->loader->add_filter( 'wp_admin_bar_class', $this, 'wp_admin_bar_class' );
                $this->loader->add_action( 'admin_bar_menu', $this, 'admin_bar_menu' );
                $this->loader->add_action( 'wp_dashboard_setup', $this, 'add_dashboard_widgets' );
                $this->loader->add_action( 'admin_head-index.php', $this, 'admin_head_index_php' );
                $this->loader->add_action( 'admin_menu', $this, 'admin_menu' );
		$this->define_admin_hooks();
		$this->define_public_hooks();

	}

	/**
	 * Load the required dependencies for this plugin.
	 *
	 * Include the following files that make up the plugin:
	 *
	 * - WP_WXTPP_Loader. Orchestrates the hooks of the plugin.
	 * - WP_WXTPP_i18n. Defines internationalization functionality.
	 * - WP_WXTPP_Admin. Defines all hooks for the admin area.
	 * - WP_WXTPP_Public. Defines all hooks for the public side of the site.
         * - WP_WXTPP_Controller. Defines all REST endpoints for WXTPP.
	 *
	 * Create an instance of the loader which will be used to register the hooks
	 * with WordPress.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function load_dependencies() {

		/**
		 * The class responsible for orchestrating the actions and filters of the
		 * core plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-wxtpp-loader.php';

		/**
		 * The class responsible for defining internationalization functionality
		 * of the plugin.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-wxtpp-i18n.php';
                
                /**
		 * The classes responsible for defining all WXTPP endpoints, core WXTPP classes.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wp-wxtpp-controller.php';
                require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wxtpp.php';
                require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wxtpp-gh.php';

		/**
		 * The class responsible for defining all actions that occur in the admin area.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/class-wp-wxtpp-admin.php';

		/**
		 * The class responsible for defining all actions that occur in the public-facing
		 * side of the site.
		 */
		require_once plugin_dir_path( dirname( __FILE__ ) ) . 'public/class-wp-wxtpp-public.php';

		$this->loader = new WP_WXTPP_Loader();

	}

	/**
	 * Define the locale for this plugin for internationalization.
	 *
	 * Uses the WP_WXTPP_i18n class in order to set the domain and to register the hook
	 * with WordPress.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function set_locale() {

		$plugin_i18n = new WP_WXTPP_i18n();

		$this->loader->add_action( 'plugins_loaded', $plugin_i18n, 'load_plugin_textdomain' );

	}
        
        /**
	 * Define the REST API endpoints for this plugin.
	 *
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function set_endpoints() {

		$controller = new WP_WXTPP_Controller();

		$this->loader->add_action( 'rest_api_init', $controller, 'register_routes' );

	}

	/**
	 * Register all of the hooks related to the admin area functionality
	 * of the plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function define_admin_hooks() {

		$plugin_admin = new WP_WXTPP_Admin( $this->get_plugin_name(), $this->get_version() );

                $this->loader->add_action( 'admin_init', $plugin_admin, 'admin_init' );
                $this->loader->add_action( is_multisite() ? 'network_admin_menu' : 'admin_menu', $plugin_admin, 'add_menus' );
		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_styles' );
		$this->loader->add_action( 'admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts' );

	}

	/**
	 * Register all of the hooks related to the public-facing functionality
	 * of the plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 */
	private function define_public_hooks() {

		$plugin_public = new WP_WXTPP_Public( $this->get_plugin_name(), $this->get_version() );

		$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_styles' );
		$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'enqueue_scripts' );

	}

	/**
	 * Run the loader to execute all of the hooks with WordPress.
	 *
	 * @since    1.0.0
	 */
	public function run() {
		$this->loader->run();                
	}

	/**
	 * The name of the plugin used to uniquely identify it within the context of
	 * WordPress and to define internationalization functionality.
	 *
	 * @since     1.0.0
	 * @return    string    The name of the plugin.
	 */
	public function get_plugin_name() {
		return $this->plugin_name;
	}

	/**
	 * The reference to the class that orchestrates the hooks with the plugin.
	 *
	 * @since     1.0.0
	 * @return    WP_WXTPP_Loader    Orchestrates the hooks of the plugin.
	 */
	public function get_loader() {
		return $this->loader;
	}

	/**
	 * Retrieve the version number of the plugin.
	 *
	 * @since     1.0.0
	 * @return    string    The version number of the plugin.
	 */
	public function get_version() {
		return $this->version;
	}
        
        public function login_form() {
            if ( !is_user_logged_in() ) {
                $wxtpp = WXTPP::get_instance();
                $pre_auth_code = $wxtpp->get_pre_auth_code();                
                $current_url = home_url( add_query_arg( array() ) );
                $url_array = parse_url( $current_url );
                $callback_url_encoded = urlencode( "{$url_array[ 'scheme' ]}://{$url_array[ 'host' ]}{$url_array[ 'path' ]}" );
                $component_appid = $wxtpp->get_component_appid();
                $component_login_url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$component_appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$callback_url_encoded}";
                $loginimgurl = plugin_dir_url( dirname( __FILE__) ) . 'assets/images/wxtpp_login.png';
                echo "<p><a href='{$component_login_url}'><img src='{$loginimgurl}' style='width:100%'></a></p>";
            }
        }

        public function login_head() {
            if ( isset($_GET[ 'auth_code' ]) ) {
                $auth_code = $_GET[ 'auth_code' ];
                $wxtpp = WXTPP::get_instance();

                $wxtpp->clear_pre_auth_code();
                $auth_info = $wxtpp->api_component_query_auth( $auth_code );
                if ( FALSE !== $auth_info ) {
                    $wxtpp_gh = new WXTPP_GH( $auth_info[ 'authorization_info' ][ 'authorizer_appid' ] );
                    $wxtpp_gh->set_access_token( $auth_info[ 'authorization_info' ][ 'authorizer_access_token' ], time() + $auth_info[ 'authorization_info' ][ 'expires_in' ] - 200 );
                    $wxtpp_gh->set_refresh_token( $auth_info[ 'authorization_info' ][ 'authorizer_refresh_token' ] );
                    $wxtpp_gh->set_authorized( TRUE );
                    
                    $user = get_user_by( 'login', $auth_info[ 'authorization_info' ][ 'authorizer_appid' ] );
                    if ( false === $user ) {
                        $authorizer_info = $wxtpp_gh->get_authorizer_info();
                        if ( false !== $authorizer_info ) {
                            $authorizer_info = $authorizer_info[ 'authorizer_info' ];
                            $user_id = wp_insert_user( [
                                'user_login' => $auth_info[ 'authorization_info' ][ 'authorizer_appid' ],
                                'user_email' => $auth_info[ 'authorization_info' ][ 'authorizer_appid' ] . '@wxtpp.com',
                                'user_pass' => 'wxtpp123456',
                                'user_nicename' => $authorizer_info[ 'user_name' ],
                                'display_name' => $authorizer_info[ 'nick_name' ],
                            ] );
                        } else {
                            $user_id = wp_create_user( $auth_info[ 'authorization_info' ][ 'authorizer_appid' ], 'wxtpp123456' );  
                        }                        
                        if ( ! is_wp_error( $user_id ) ) {
                            delete_user_option( $user_id, 'capabilities' );
                            delete_user_option( $user_id, 'user_level' );
                            add_user_to_blog( $wxtpp_gh->get_siteid(), $user_id, 'administrator' );
                        }
                    } else {
                        $user_id = $user->ID;
                    }
                    
//                    $site_homeurl = get_home_url( $wxtpp_gh->get_siteid() );
                    $site_adminurl = get_admin_url( $wxtpp_gh->get_siteid() );
                    wp_clear_auth_cookie();
                    wp_set_auth_cookie( $user_id, true );
                    wp_set_current_user( $user_id );
                    wp_redirect( $site_adminurl );
                    exit();
                }
            } else {
                $logo_url = plugin_dir_url( dirname( __FILE__ ) ). 'assets/images/wxtpp_logo.png';
                echo "<style>.login h1 a { background-image:url('{$logo_url}') !important; } </style>";
            }
        }
        
        public function get_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
//            error_log( __METHOD__ . '#' . __LINE__ );
//            error_log( print_r( $id_or_email, true ) );
            $user = false;
            if ( is_numeric( $id_or_email ) ) {
                $user = get_user_by( 'id' , ( int ) $id_or_email );
            } elseif ( is_object( $id_or_email ) ) {
                if ( ! empty( $id_or_email->user_id ) ) {
                    $user = get_user_by( 'id' , (int) $id_or_email->user_id );
                }
            } else {
                $user = get_user_by( 'email', $id_or_email );	
            }
            
            if ( $user ) {
                $site_id = get_id_from_blogname( $user->user_login );
                if ( is_null( $site_id ) ) {
                    return "<img alt='{$alt}' src='http://usr.im/{$size}x{$size}' class='avatar avatar-{$size} photo' />";
                } else {
                    $wxtpp_gh = new WXTPP_GH( $user->user_login );
                    $authorizer_info = $wxtpp_gh->get_authorizer_info();
//                    error_log( print_r( $authorizer_info, true ) );
                    if ( false !== $authorizer_info ) {
                        $authorizer_info = $authorizer_info[ 'authorizer_info' ];
                        return "<img alt='{$alt}' src='{$authorizer_info[ 'head_img' ]}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
                    } else {
                        return "<img alt='{$alt}' src='http://usr.im/{$size}x{$size}' class='avatar avatar-{$size} photo' />";
                    }
                }
            }
            return $avatar;
        }
        
        public function admin_footer_text( $content ) {
            $text = __('wosotech', 'wp-wxtpp') . ' &copy; ' . date('Y');
            return '<span id="footer-thankyou">' . $text . '</span>';
        }
        
        public function update_footer( $content ) {
//            error_log( __METHOD__ );
            return $this->plugin_name . '&nbsp;'.$this->version;
        }
        
        public function add_admin_bar_menus() {
            global $wp_admin_bar;
//            error_log( print_r( $wp_admin_bar, true ) );
            remove_action( 'admin_bar_menu', 'wp_admin_bar_wp_menu' );
            remove_action( 'admin_bar_menu', 'wp_admin_bar_my_sites_menu' );
            remove_action( 'admin_bar_menu', 'wp_admin_bar_site_menu' );
            remove_action( 'admin_bar_menu', 'wp_admin_bar_comments_menu' );
            remove_action( 'admin_bar_menu', 'wp_admin_bar_new_content_menu' );
            error_log( print_r( $wp_admin_bar, true ) );
            
            add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ), 5 );
        }
        
        public function admin_bar_menu( $wp_admin_bar ) {
            if ( is_user_logged_in() ) {
//                    $logo_url = plugin_dir_url( dirname( __FILE__ ) ). 'assets/images/wxtpp_logo.png';
                    $wp_admin_bar->add_menu( array(
                            'id'     => 'wxtpp-logo',
//                            'title'  => "<img src='{$logo_url}' class='avatar avatar-26' style='line-height:32px;width:26px;height:26px' /><span style='line-height:32px;'>TWP -" .esc_html__('TWP', 'wp-wxtpp') .'</span>',
                            'title' => esc_html__('TWP', 'wp-wxtpp'),
                            'href'   => admin_url() 
                    ) );
            }
        }
        
        public function wp_admin_bar_class() {
            require_once plugin_dir_path( dirname( __FILE__) ) . 'includes/class-wp-wxtpp-admin-bar.php';
            return 'WP_WXTPP_Admin_bar';
        }
        
        public function add_dashboard_widgets() {
            global $current_blog;
            global $wp_meta_boxes;
            
            if ( ! is_network_admin() && 1 != $current_blog->blog_id ) {
//                error_log( print_r( $wp_meta_boxes, true ) );
                unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now'] );
                unset( $wp_meta_boxes['dashboard']['normal']['core']['dashboard_activity'] );
                unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press'] );
                unset( $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary'] );
                remove_action( 'welcome_panel', 'wp_welcome_panel' );
                
//                $screen = get_current_screen();
//                $screen->remove_help_tabs();
                
                wp_add_dashboard_widget( 'wxtpp_gh_baseinfo', __('WXTPP GH base info', 'wp-wxtpp'), [ $this, 'wxtpp_gh_baseinfo' ] );
            }
        }
        
        public function wxtpp_gh_baseinfo() {
            global $current_blog;
            if ( ! is_network_admin() && 1 != $current_blog->blog_id ) {                
//                error_log( print_r( $current_blog, true ) );
                $appid = get_option( 'blogname' );
//                error_log( print_r( $appid, true ) );
                $wxtpp_gh = new WXTPP_GH( $appid );
                $authorizer_info = $wxtpp_gh->get_authorizer_info();
                if ( false !== $authorizer_info ) {
                    error_log( print_r( $authorizer_info, true ) );
                    $authorization_info = $authorizer_info[ 'authorization_info' ];
                    $authorizer_info = $authorizer_info[ 'authorizer_info' ];
                    $checked = '<i class="fa fa-check-square-o" style="color:green;"></i>';
                    $closed = '<i class="fa fa-window-close-o" style="color:red;"></i>';
                ?>
<div  class="table table_authorizer">
    <p class="sub"><?php esc_html_e( 'Authorizer Info', 'wp-wxtpp' ); ?></p>
    <table>
        <tr>
            <td class="key">头像</td>
            <td class="value"><img src="<?php echo $authorizer_info[ 'head_img' ]; ?>" style="width:50px; height:50px;"></td>
        </tr>
        <tr>
            <td class="key">名称</td>
            <td class="value"><?php echo $authorizer_info[ 'nick_name' ]; ?></td>
        </tr>
        <tr>
            <td class="key">微信号</td>
            <td class="value"><?php echo $authorizer_info[ 'alias' ]; ?></td>
        </tr>
        <tr>
            <td class="key">原始ID</td>
            <td class="value"><?php echo $authorizer_info[ 'user_name' ]; ?></td>
        </tr>
        <tr>
            <td class="key">类型</td>
            <td class="value"><?php echo WXTPP_GH::get_service_type_info_str( $authorizer_info[ 'service_type_info' ][ 'id' ] ); ?></td>
        </tr>
        <tr>
            <td class="key">认证情况</td>
            <td class="value"><?php echo WXTPP_GH::get_verify_type_info_str( $authorizer_info[ 'verify_type_info' ][ 'id' ] ); ?></td>
        </tr>
        <tr>
            <td class="key">微信门店</td>
            <td class="value"><?php echo $authorizer_info[ 'business_info' ][ 'open_store' ] ? $checked : $closed; ?></td>
        </tr>
        <tr>
            <td class="key">微信扫商品</td>
            <td class="value"><?php echo $authorizer_info[ 'business_info' ][ 'open_scan' ] ? $checked : $closed; ?></td>
        </tr>
        <tr>
            <td class="key">微信支付</td>
            <td class="value"><?php echo $authorizer_info[ 'business_info' ][ 'open_pay' ] ? $checked : $closed; ?></td>
        </tr>
        <tr>
            <td class="key">微信卡券</td>
            <td class="value"><?php echo $authorizer_info[ 'business_info' ][ 'open_card' ] ? $checked : $closed; ?></td>
        </tr>
        <tr>
            <td class="key">微信摇一摇</td>
            <td class="value"><?php echo $authorizer_info[ 'business_info' ][ 'open_shake' ] ? $checked : $closed; ?></td>
        </tr>
    </table>
</div>
    <div class="table table_authorization">
        <p class="sub"><?php esc_html_e( 'Authorization Info', 'wp-wxtpp' ); ?></p>
        <table>
            <tr>
                <td class='key'>AppID</td>
                <td class="value"><?php echo $authorization_info[ 'authorizer_appid' ]; ?></td>
            </tr>
            <tr>
                <td class='key'>消息管理权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][0] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>用户管理权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][1] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>帐号服务权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][2] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>网页服务权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][3] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信小店权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][4] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信多客服权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][5] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>群发与通知权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][6] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信卡券权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][7] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信扫一扫权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][8] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信连WIFI权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][9] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>素材管理权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][10] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信摇周边权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][11] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信门店权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][12] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>微信支付权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][13] ? $checked : $closed; ?></td>
            </tr>
            <tr>
                <td class='key'>自定义菜单权限</td>
                <td class="value"><?php echo $authorization_info[ 'func_info' ][14] ? $checked : $closed; ?></td>
            </tr>
        </table>
    </div>
                <br class="clear" />
                <?php
                }
            }
        }
        
        public function admin_head_index_php() {
//            global $hook_suffix;
//            error_log( __METHOD__ . '$hook_suffix = '. $hook_suffix );
            $screen = get_current_screen()->remove_help_tabs();
        }
        
        public function admin_menu() {
            add_menu_page( __( 'Wechat Function', 'wp-wxtpp' ), __( 'Wechat Function', 'wp-wxtpp' ), 'manage_options', 'wechat_function', null, 'dashicons-screenoptions' );
            add_submenu_page( 'wechat_function', __( 'Autoreply', 'wp-wxtpp' ), __( 'Autoreply', 'wp-wxtpp' ), 'manage_options', 'wechat_autoreply' );
            add_submenu_page( 'wechat_function', __( 'Menu', 'wp-wxtpp' ), __( 'Menu', 'wp-wxtpp' ), 'manage_options', 'wechat_menu' );
            
            add_menu_page( __( 'Wechat Management', 'wp-wxtpp' ), __( 'Wechat Management', 'wp-wxtpp' ), 'manage_options', 'wechat_management', '', 'dashicons-layout' );
            add_menu_page( __( 'Wechat Statistics', 'wp-wxtpp' ), __( 'Wechat Statistics', 'wp-wxtpp' ), 'manage_options', 'wechat_statistics', '', 'dashicons-chart-pie' );
            add_menu_page( __( 'Wechat Settings', 'wp-wxtpp' ), __( 'Wechat Settings', 'wp-wxtpp' ), 'manage_options', 'wechat_settings', '', 'dashicons-admin-generic' );
            add_menu_page( __( 'Wechat Development', 'wp-wxtpp' ), __( 'Wechat Development', 'wp-wxtpp' ), 'manage_options', 'wechat_development', '', 'dashicons-admin-tools' );
        }
}
